#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <string>
#include <vector>
using namespace std;

pthread_cond_t gcond = PTHREAD_COND_INITIALIZER;//条件变量
pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;//互斥锁

void* SlaverCore(void* args)
{
    string name = (char*)args;
    while(true)
    {
        pthread_mutex_lock(&gmutex);
        //一般条件变量是在加锁和解锁之间使用的
        pthread_cond_wait(&gcond,&gmutex);//gmutex：这个是用来释放的【前一半】
        cout << "当前被叫醒的线程是：" << name << endl;
        pthread_mutex_unlock(&gmutex);
    }
}

void* MasterCore(void* args)
{
    sleep(3);
    cout << "master 开始工作....." << endl;
    string name = (char*)args;
    while(true)
    {
        //pthread_cond_signal(&gcond);
        pthread_cond_broadcast(&gcond);//唤醒说有
        sleep(1);
        cout << "master 唤醒一个线程..." << endl;
        // cout << name << endl;
        // sleep(1);
    }
}

void StartMaster(vector<pthread_t>* tidsptr)
{
    pthread_t tid;
    int n = pthread_create(&tid,nullptr,MasterCore,(void*)"Mastre Thread");

    if(n == 0)
    {
        cout << "create mastre success" << endl;
    }
    
    tidsptr->push_back(tid);

}

void StartSlaver(vector<pthread_t>* tidsptr,int threadnum = 3)
{
    for(int i = 0; i < threadnum; i++)
    {
        char* name = new char[64];
        snprintf(name,64,"Slaver-%d",i + 1);
        pthread_t tid;
        int n = pthread_create(&tid,nullptr,SlaverCore,(void*)name);
        if(n == 0)
        {
            cout << "create success" << name << endl;
            tidsptr->push_back(tid);
        }
    }
}

void WaitThread(vector<pthread_t>& tidsptr)
{
    for(auto& e: tidsptr)
    {
        pthread_join(e,nullptr);
    }
}

int main()
{
    vector<pthread_t> tids;

    StartMaster(&tids);
    StartSlaver(&tids,5);

    WaitThread(tids);
    return 0;
}

